<template>
	<div class="index-box">
		<el-form label-width="200px" :model="formItem" ref="formItem" :rules="rules" class="formBlock">
     <!-- <el-form-item label="广告分类" prop="typeId">
      	<treeselect v-model="formItem.typeId" :options="treeList" :normalizer="normalizer" placeholder="选择商品分类" />
      </el-form-item> -->
			<el-form-item label="banner名称" prop="name">
				<el-input type="text" v-model="formItem.name" placeholder="名称" clearable class="textInput"></el-input>
			</el-form-item>
		<!-- 	<el-form-item label="上传图片" prop="image" v-if="formItem.typeId=='1'">
				<MyUpImg :imagePreview='formItem.image'  @change="imageChange($event, 'image')"  imageSize="chang"></MyUpImg>
				<p style="color: red;margin: 0px;">图片规格必须为：宽 700px、高280px，宽 340px、高530px</p>
			</el-form-item> -->
      <el-form-item label="上传图片" prop="image">
      	<MyUpImg :imagePreview='formItem.image'  @change="imageChange($event, 'image')"></MyUpImg>
        	<p style="color: red;margin: 0px;">图片规格必须为：宽 690px、高260px</p>
      </el-form-item>

			<el-form-item label="跳转方式" prop="linkType">
        <el-radio-group v-model="formItem.linkType" @change="radioChange">
          <el-radio  label="0">链接地址</el-radio>
          <el-radio  label="1">绑定商品</el-radio>
          <el-radio  label="2">绑定门店</el-radio>
         <!-- <el-radio  label="3">云仓商品</el-radio> -->
        </el-radio-group>
			</el-form-item>

			<el-form-item label="链接地址" prop="link" v-if="formItem.linkType==0">
				<el-input type="text" v-model="formItem.link" placeholder="链接地址" clearable class="textInput"></el-input>
			</el-form-item>
      <el-form-item label="绑定商品" prop="link" v-if="formItem.linkType==1">
          {{formItem.productName}}
          <el-button size="small" type="primary" @click="handleShowShop">选择商品</el-button>
      </el-form-item>
      <el-form-item label="绑定门店" prop="link" v-if="formItem.linkType==2">
          {{formItem.storeName}}
          <el-button size="small" type="primary" @click="handleShowStore">选择门店</el-button>
      </el-form-item>
      <!-- <el-form-item label="云仓商品ID" prop="link" v-if="formItem.linkType==3">
          <el-input type="text" v-model="formItem.link" placeholder="云仓商品ID" clearable class="textInput"></el-input>
      </el-form-item> -->
     <!-- <el-form-item label="有效期" prop="validityFlag">
        <el-radio-group v-model="formItem.validityFlag" @change="handleChangeTime">
          <el-radio  :label="1">长期</el-radio>
          <el-radio  :label="2">自定义时间</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="自定义时间" prop="time" v-if="formItem.validityFlag=='2'" >
          <el-date-picker v-model="formItem.time" type="daterange" align="right" unlink-panels range-separator="至" v-if="dateShow"
            start-placeholder="自定义开始日期" end-placeholder="自定义结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
          </el-date-picker>
      </el-form-item> -->


			<el-form-item label="排序" prop="sortOrder">
				<el-input-number v-model="formItem.sortOrder" :min="1" label="排序" class="textInput"></el-input-number>
			</el-form-item>
      <el-form-item label="发布人" v-if="type=='edit'">
      	{{formItem.releaseName}}({{formItem.releaseTelephone}})
      </el-form-item>

			<!-- <el-form-item label="内容">
           <QuillEditor :value.sync="formItem.description" />
			</el-form-item> -->

			<el-form-item>
				<el-button type="primary" @click="save('formItem')" :loading="submitLoading" v-if="type!='look'">保 存</el-button>
				<el-button icon="el-icon-back" @click="back">返 回</el-button>
			</el-form-item>

			<!--	选择商品	-->
			<el-dialog title="选择商品" :visible.sync="productsDialogVisible" :close-on-click-modal="false" v-dialogDrag>
        <div class="search-box">
          <el-form :inline="true" :model="shopDialog" size="small" ref="shopDialog" @submit.native.prevent
            class="demo-form-inline d-flex " id="searchBox"  style="flex-wrap: wrap;">
            <el-form-item prop="goodsCode" style="width:200px">
                <el-input v-model="shopDialog.goodsCode" clearable placeholder="商品编号"></el-input>
            </el-form-item>
            <el-form-item prop="goodsName" style="width:200px">
                <el-input v-model="shopDialog.goodsName" clearable placeholder="商品名称"></el-input>
            </el-form-item>
           <el-form-item prop="storeName" style="width:200px">
              <el-input v-model="shopDialog.storeName" clearable placeholder="商家门店名称"></el-input>
            </el-form-item>

            <el-form-item class="clearfix">
              <el-button type="primary" @click="handleShopSearch()" icon="el-icon-search">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
				<el-row :gutter="20">
					<el-col :span="4" v-for="(item, index) in shopDialogList" :key="index">
						<el-card :body-style="{ padding: '0px' }" :shadow="item.id == formItem.product_id ? 'always' : 'hover'" style="margin-bottom: 10px;">
							<img :src="item.goodsImage" height="185">
							<div style="padding: 14px;">
								<p style="height: 40px;line-height: 20px;margin-bottom: 15px;" class="ellipsis-item2">{{item.goodsName}}({{item.goodsCode}})</p>
								<el-button size="small" @click="changeProduct(item)">选择</el-button>
							</div>
						</el-card>
					</el-col>
				</el-row>
        <MyPagination
          :total="shopDialog.total"
          :page.sync="shopDialog.pageNum"
          :limit.sync="shopDialog.pageSize"
          @pagination="getShopList"
        />
				<div slot="footer" class="dialog-footer">
					<el-button size="small" @click="productsDialogVisible = false">取 消</el-button>
				</div>
			</el-dialog>
			<!--	选择商品	-->

      <!--	选择门店	-->
      <el-dialog title="选择门店" :visible.sync="storeVisible" :close-on-click-modal="false" v-dialogDrag>
        <div class="search-box">
          <el-form :inline="true" :model="dialog" size="small" ref="dialog" @submit.native.prevent
            class="demo-form-inline d-flex " id="searchBox" style="flex-wrap: wrap;">
            <el-form-item prop="storeName" style="width:200px">
                <el-input v-model="dialog.storeName" clearable placeholder="商家名称"></el-input>
            </el-form-item>

            <el-form-item class="clearfix">
              <el-button type="primary" @click="handleDialogSearch()" icon="el-icon-search">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      	<el-row :gutter="20" v-loading = "dialogLoading">
      		<el-col :span="4" v-for="(item, index) in storeList" :key="index">
      			<el-card :body-style="{ padding: '0px' }" :shadow="item.id == formItem.product_id ? 'always' : 'hover'" style="margin-bottom: 10px;">
      				<img :src="item.storeLogo" style="height:185px; overflow: hidden;display: block;">
      				<div style="padding: 14px;">
      					<p style="height: 40px;line-height: 20px;margin-bottom: 15px;" class="ellipsis-item2">{{item.storeName}}</p>
      					<el-button size="small" @click="checkStore(item)">选择</el-button>
      				</div>
      			</el-card>
      		</el-col>
      	</el-row>
        <MyPagination
          :total="dialog.total"
          :page.sync="dialog.pageNum"
          :limit.sync="dialog.pageSize"
          @pagination="getStoreList"
        />
      	<div slot="footer" class="dialog-footer">
      		<el-button size="small" @click="storeVisible = false">取 消</el-button>
      	</div>
      </el-dialog>
      <!--	选择门店	-->
		</el-form>
	</div>
</template>

<script>
 import VueUeditorWrap from 'vue-ueditor-wrap'
 import Treeselect from "@riophae/vue-treeselect";
 import "@riophae/vue-treeselect/dist/vue-treeselect.css";
 import QuillEditor from '@/components/QuillEditor/quillEditor'
 import { BaddBanner,BgetStoreList,BgoodsGetList } from '@/api/getData';
	export default {
		name: 'ad_banner_insert',
    components: { Treeselect,QuillEditor },
		data() {
      var links = (rule, value, callback) => {
        if (value === '' && this.formItem.linkType=='0') {
          callback(new Error('请输入链接地址'));
        }else if (value === '' && this.formItem.linkType=='1') {
          callback(new Error('请绑定商品'));
        }else if (value === '' && this.formItem.linkType=='2') {
          callback(new Error('请绑定门店'));
        }else if (value === '' && this.formItem.linkType=='3') {
          callback(new Error('请输入云仓商品ID'));
        }else {
          callback();
        }
      };
			return {
        dateShow:true,
        loading:false,
        dialogLoading:false,
        submitLoading:false,
        productsDialogVisible:false,
        products:[],
        statusRow:{},
				/*		表单数据		*/
				formItem: {
					typeId: undefined,
					name: "",
          image:'',
          linkType:'0',//0是链接 1是产品
          validityFlag:1,
          time:[],
          validityStartDate:"",
          validityEndDate:'',
          link:'',
          productId:'',
          appId:'',
          sortOrder:'',
          description:"",

          storeName:'',
          storeId:''
				},
        dialog:{
          storeName:"",
          total:0,
          pageNum:1,
          pageSize:20,
        },
        shopDialog:{
          goodsCode:"",
          goodsName:'',
          storeName: '',
          total:0,
          pageNum:1,
          pageSize:20,
        },
        treeList:[],
        rules: {
          typeId: [{required: true, message: '请选择广告分类',trigger: 'blur'}],
          name: [{required: true, message: '请输入广告名称',trigger: 'blur'}],
          validityFlag: [{required: true, message: '请选择有效期',trigger: 'blur'}],
          time: [{required: true, message: '请选择自定义时间',trigger: 'blur'}],
          image: [{required: true, message: '请上传图片',trigger: 'blur'}],
          link: [{required: true, validator:links,trigger: 'blur'}],
          productId: [{required: true, message: '请上传产品',trigger: 'blur'}],
          storeId: [{required: true, message: '请选中门店',trigger: 'blur'}],
          appId: [{required: true, message: '请选中应用端',trigger: 'blur'}],
          sortOrder: [{required: true, message: '请输入排序',trigger: 'blur'}],
        },
        bannerId:'',
        type:'',

        storeVisible:false,
        storeList:[],
        storeTypeList:[],
        shopTypeList:[],
        shopDialogList:[],
        itemKey:"1"
			}
		},
		mounted() {
			this.bannerId = this.$route.query.bannerId;
      this.type = this.$route.query.type;
      if(this.bannerId){
        this.dataInfo();
      }
      //this.getSelect();
		},
		methods: {
      handleChangeTime(){
        if(this.formItem.validityFlag=='2'){
          this.dateShow = true;
        }else{
          this.dateShow = false;
        }
      },
      /*		退出当前界面		*/
			back() {
        this.$router.go(-1);
			},
      radioChange(){
          this.formItem.link = '';
          this.$refs["formItem"].clearValidate();
      },
      handleShowShop(){
        this.productsDialogVisible = true;
        this.getCategoryDetails({categoryKey:'product_category'})
        .then(res=>{
          this.shopTypeList = [{
            categoryId:'',
            children: res.data,
            name: "商品分类",
          }];
          console.log( this.shopTypeList)
        })
        this.getShopList();
      },
      normalizer1(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.name,
          children: node.children
        };
      },
      normalizer2(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.name,
          children: node.children
        };
      },
      handleDialogSearch(){
        this.dialog.pageNum = 1;
        this.getStoreList();
      },
      handleShopSearch(){
        this.shopDialog.pageNum = 1;
         this.getShopList();
      },
      checkStore(row){
        //this.statusRow = row;
        this.formItem.storeName = row.storeName;
        this.formItem.link = row.storeId;
        this.storeVisible = false;
      },
      handleShowStore(){
        this.storeVisible = true;
        // this.getCategoryDetails({categoryKey:'product_category'})
        // .then(res=>{
        //   this.shopTypeList = [{
        //     categoryId:'',
        //     children: res.data,
        //     name: "商品分类",
        //   }];
        //   console.log( this.shopTypeList)
        // })
        this.getStoreList();
      },
      async getStoreList(){
        try {
          this.dialogLoading = true;
          let data = {pageNum: this.dialog.pageNum,pageSize: this.dialog.pageSize,storeName:this.dialog.storeName};
          console.log(data);
          const result = await BgetStoreList(data);
          if (result.code == 200) {
            this.dialog.total = result.total;
            this.storeList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.dialogLoading = false;
        } catch (err) {
          this.dialogLoading = false;
          console.log(err)
        }
      },
      async getShopList(){
        try {
          this.dialogLoading = true;
          let data = {pageNum: this.shopDialog.pageNum,pageSize: this.shopDialog.pageSize,auditStatus: "2",goodsCode:this.shopDialog.goodsCode,goodsName:this.shopDialog.goodsName,storeName:this.shopDialog.storeName};

          const result = await BgoodsGetList(data);
          if (result.code == 200) {
            this.shopDialog.total = result.total;
            this.shopDialogList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.dialogLoading = false;
        } catch (err) {
          this.dialogLoading = false;
          console.log(err)
        }
      },
      dataInfo(){
        getAdvertisDetails({bannerId:this.bannerId}).then(res=>{
          if(res.code == 200){
            this.dateShow = false;
              let data = res.data;
              data.time = [];
              this.formItem = data;
              this.formItem.linkType = res.data.linkType+'';
              if(res.data.validityFlag=='2'){
                this.formItem.time = [ res.data.validityStartDate, res.data.validityEndDate ];
                this.$nextTick(()=>{
                   this.dateShow = true;
                })
              }
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      getSelect(){
        this.getCategoryDetails({categoryKey:'stores_category'}).then(res=>{ this.storeTypeList = res.data; })
        this.getCategoryDetails({categoryKey:'advertising_category'})/*左边 商品分类*/
        .then(res=>{
          this.treeList = [{
            typeId: '',
            children: res.data,
            name: "广告分类",
          }];
        })
      },
      changeProduct(row){
        //this.statusRow = row;
        this.formItem.productName = row.goodsName;
        this.formItem.link = row.goodsId;
        this.productsDialogVisible = false;
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.typeId,
          label: node.name,
          children: node.children
        };
      },
			/*		保存数据		*/
			save(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = JSON.parse(JSON.stringify(this.formItem))
            if(data.validityFlag=='2'){
              data.validityStartDate = this.formItem.time[0];
              data.validityEndDate = this.formItem.time[1];
            }
            let res = {
              bannerId:data.appId,
              bannerImage:data.image,
              bannerName:data.name,
              bannerType:data.linkType,
              bindLink:data.link,
              orderSort:data.sortOrder
            }
            this.userLoading = true;
            BaddBanner(res).then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);
                this.$router.go(-1);
              } else {
                this.$message.error(result.msg);
              }
              this.userLoading = false;
            });
          }
        })
			},
			imageChange(path, name) {
				this.formItem[name] = path
			}
		}
	}
</script>
<style scoped lang="scss">
    .index-box{
      height: 100%;
      overflow-y: auto;
    }
</style>
